<template>
  <div>
    <el-card class="search-card">
      <basic-form
        ref="formData"
        defaultExpandStatus
        formItemWidth="130px"
        :formColumns="formItems"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        :handleClearForm="clearCategorySelect"
        @getFormData="getFormData"
      >
        <CategoryMultipleSelect
          slot="category"
          ref="categoryMultiple"
          @selectCategoryCallback="setFormCateUuids"
        />
      </basic-form>
    </el-card>
    <el-card class="table-card">
      <skus-table
        ref="skusTable"
        showActionCol
        showPagination
        :tableHeight="480"
        :defaultMinWidth="100"
        :actionColWidth="150"
        :dataSource="TableInfo.list"
        :columns="TableInfo.columns"
        :loading="TableInfo.loading"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="pagination.total"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <!-- 按钮操作栏 -->
        <BtnRender slot="content_context" :render="renderBtnsBar" />
      </skus-table>
    </el-card>
    <SelectEditInfoTempDialog
      :visible.sync="selectEditInfoTemp.visible"
      @getPageName="redirectEditPage"
    />
  </div>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import CategoryMultipleSelect from '@/components/Category/MultipleSelect';
import SelectEditInfoTempDialog from '@/pages/commodity/components/SelectEditInfoTempDialog';
import skusPage from '@/mixins/commodity/skusPage';
import { getListPageBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import { getInitFormData, TableInfo } from '@/utils/getUtils';
import { setAuthBtnId, createExcelByExport, generateUuid } from '@/utils/bizUtils';
import { FORM_ITEMS, TABLE_COLUMNS } from './constants/list';
import { PageNameMaps, EDIT_RADIO_GROUP_VALUES } from '@/pages/commodity/components/SelectEditInfoTempDialog/constants';
import {
  getSkuListForSkuManageService,
  exportSkuManageService,
} from '@/api/commodity/commodityManage/skuManage';
import { checkPermService } from '@/api/commodity/common';
export default {
  mixins: [skusPage],
  components: {
    BasicDialog,
    BasicForm,
    SkusTable,
    BtnRender,
    CategoryMultipleSelect,
    SelectEditInfoTempDialog
  },
  data () {
    return {
      formItems: FORM_ITEMS,
      formData: getInitFormData(FORM_ITEMS),
      TableInfo: new TableInfo({ columns: TABLE_COLUMNS }),
      pageSizes: [10, 50, 100, 1000],
      btnLoading: {
        export: false
      },
      selectEditInfoTemp: {
        visible: false, // 修改信息模板弹框开关
        skuNo: '', // 当前要修改的skuNo
        productUuid: '',
      }
    }
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      // 按钮通用属性填充
      const btnBars = [
        {
          label: '导出',
          method: this.handleExport,
          loading: this.btnLoading.export,
          hasAuth: true
        }
      ]
      return getListPageBtnsBar(h, btnBars, this.showBtn, 'start')
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const actionList = [
        { label: '修改', method: this.handleEdit, hasAuth: true },
        { label: '查看', method: this.handleView },
        { label: '图文', method: this.handleGraphic, hasAuth: true }
      ]
      return getTableAction({ h, row, actionList, showBtn: this.showBtn })
    },
    // 导出
    async handleExport () {
      if (this.validateFormIsNull()) return this.$message.warning('请至少输入一个筛选项')
      setAuthBtnId('导出')
      const data = this.formData
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await exportSkuManageService(data, loadingFn)
      createExcelByExport({ excelTitle: `SKU管理列表_${generateUuid()}`, res })
    },
    // 批量导入分销商品
    handleBatchImport () {
      this.batchImport.visible = true
    },
    // 编辑
    async handleEdit (row) {
      const data = { spuNo: row.spuNo }
      const res = await checkPermService(data, this.TableInfo.setLoading)
      if (res?.retData == 'ok') {
        this.selectEditInfoTemp.visible = true
        this.selectEditInfoTemp.skuNo = row.skuNo
        this.selectEditInfoTemp.productUuid = row.productUuid
      }
    },
    // 查看
    handleView (row) {
      this.openBlankPage({
        name: 'SPUManageDetail',
        query: { productUuid: row.productUuid, spuNo: row.spuNo }
      })
    },
    // 图文
    handleGraphic (row) {
      this.openBlankPage({
        name: 'chageFromManageImageText',
        query: {
          productUuid: row.productUuid,
          productName: row.productNameFinal,
          spuNo: row.spuNo,
          fromType: 'single'
        }
      })
    },
    // 跳转对应修改模板页面
    redirectEditPage (pageName) {
      this.selectEditInfoTemp.visible = false
      let query = { uuid: this.selectEditInfoTemp.productUuid, type: 'single_sku' }
      if (pageName == PageNameMaps[EDIT_RADIO_GROUP_VALUES.SkuInfo]) {
        query = { skuNo: this.selectEditInfoTemp.skuNo, type: 'single_sku' }
      }
      this.openBlankPage({ name: pageName, query })
    },
    // 获取查询入参
    getSearchParams () {
      const data = _.omit({
        ...this.formData,
        categoryUuidsStr: this.formData.categoryUuids.join(','),
        ...this.paginationParams,
      }, ['categoryUuids'])
      return data
    },
    // 获取表格数据 by 查询表单
    async getTableData () {
      setAuthBtnId('查询')
      this.executeSearchKeyword()
      const data = this.getSearchParams()
      const res = await getSkuListForSkuManageService(data, this.TableInfo.setLoading)
      if (res?.retData) {
        this.TableInfo.setList(res.retData.results)
        this.setTotalNum(res.retData.totalNum)
      }
    },
    // 校验表格是否为空
    validateFormIsNull () {
      const isNullForm = Object.values(this.formData).every(val => {
        if (Array.isArray(val)) return val.length == 0
        return !val
      })
      return isNullForm
    },
    // 获取品类集合
    setFormCateUuids (list) {
      this.formData.categoryUuids = list.map(item => item.categoryUuid)
    },
    // 清空品类选择信息
    clearCategorySelect () {
      this.$refs.categoryMultiple.clearSelectResult()
    },
    // 打开新空白页
    openBlankPage (data) {
      const { href } = this.$router.resolve(data)
      window.open(href, '_blank')
    },
    // 处理智能搜索关键词逻辑
    executeSearchKeyword () {
      this.pageSizes = this.formData.searchKeyword ? [10, 50, 100] : [10, 50, 100, 1000]
      // 智能搜索关键词时，每页展示条数最大为100
      if (this.formData.searchKeyword && this.paginationParams.pageShow == 1000) {
        this.paginationParams.pageShow = 10
      }
    }
  }
}
</script>
